﻿using BootyBay.PrivateStoreApp.AgentServicesRef;
using BootyBay.PrivateStoreApp.Common;
using BootyBay.PrivateStoreApp.DataModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.UI.Xaml;

namespace BootyBay.PrivateStoreApp.ViewModels
{
    public class DownloadAppsPageVM : BindableBase
    {
        #region Instance
        private static DownloadAppsPageVM instance = null;
        public static DownloadAppsPageVM Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new DownloadAppsPageVM();
                }
                return instance;
            }
        }
        #endregion

        #region 对象声明

        private DispatcherTimer timer = new DispatcherTimer();//定时器：下载进度
        private DispatcherTimer timer2 = new DispatcherTimer();//定时器：移除安装完成的应用

        private AppListPageVM m_AppListPageVM;

        public AppListPageVM AppListPageVM
        {
            get { return m_AppListPageVM; }
            set { SetProperty(ref m_AppListPageVM, value); }
        }

        private ObservableCollection<DownloadAppsPageVM> m_DownloadApps = new ObservableCollection<DownloadAppsPageVM>();

        public ObservableCollection<DownloadAppsPageVM> DownloadApps
        {
            get { return m_DownloadApps; }
            set { SetProperty(ref m_DownloadApps, value); }
        }

        /// <summary>
        /// 应用Id
        /// </summary>
        private int id;

        public int Id
        {
            get { return id; }
            set { SetProperty(ref id, value); }
        }

        /// <summary>
        /// 应用名称
        /// </summary>
        private string appName;

        public string AppName
        {
            get { return appName; }
            set { SetProperty(ref appName, value); }
        }

        /// <summary>
        /// 应用50*50的logo
        /// </summary>
        private string logoUrl_Store;

        public string LogoUrl_Store
        {
            get { return logoUrl_Store; }
            set { SetProperty(ref logoUrl_Store, value); }
        }

        private int appProgressBarValue;

        public int AppProgressBarValue
        {
            get { return appProgressBarValue; }
            set { SetProperty(ref appProgressBarValue, value); }
        }

        private bool isAppDownloading = true;

        public bool IsAppDownloading
        {
            get { return isAppDownloading; }
            set { SetProperty(ref isAppDownloading, value); }
        }

        private string appDescription;

        public string AppDescription
        {
            get { return appDescription; }
            set { SetProperty(ref appDescription, value); }
        }
        #endregion

        public DownloadAppsPageVM()
        {
            timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            timer.Tick -= timer_Tick;
            timer.Tick += timer_Tick;
            timer.Start();//启动下载进度执行定时器

            timer2.Interval = new TimeSpan(0, 0, 0, 5);
            timer2.Tick -= timer2_Tick;
            timer2.Tick += timer2_Tick;
            timer2.Start();//启动应用是否安装完成的定时器
        }

        #region 定时器执行方法
        async void timer2_Tick(object sender, object e)
        {
            try
            {
                foreach (var item2 in AppListPageVM.Instance.AppData)
                {
                    AppLocalStatus appLocalStatus = await AppDetailPageVM.Instance.GetAppLocalStatus(item2);
                    foreach (DownloadAppsPageVM item in DownloadApps)
                    {
                        if (item2.AppView.Id == item.Id && appLocalStatus == AppLocalStatus.Installed)
                        {
                            AppDetailPageVM.Instance.InstallrefreshData.Add(item2.AppView.ApplicationName);
                            AppDetailPageVM.Instance.CreatTostNotification(item2.AppView.ApplicationName);
                            DownloadApps.Remove(item);
                            break;
                        }
                        else if (item2.AppView.Id == item.Id && appLocalStatus != AppLocalStatus.Processing)
                        {
                            try
                            {
                                MessageDialog msg = new MessageDialog("\"" + item2.AppView.ApplicationName + "\"" + " 应用安装未能成功！\n\n1. 查看该应用支持的处理器是否与你的计算机的处理器相符合。\n2. 联系管理员，检查该应用的安装包是否完整。");
                                await msg.ShowAsync();
                            }
                            catch (Exception)
                            {
                            }
                            DownloadApps.Remove(item);
                            break;
                        }
                        else if (item2.OptStatus == AppOperationStatus.Unauthorized)
                        {
                            try
                            {
                                MessageDialog msg = new MessageDialog("权限不足，拒绝访问!");
                                await msg.ShowAsync();
                            }
                            catch (Exception)
                            {
                            }
                            DownloadApps.Remove(item);
                            break;
                        }
                    }
                }
            }
            catch (System.InvalidOperationException)
            {
            }

            //RefreshDownloadApps();
        }
        void timer_Tick(object sender, object e)
        {
            foreach (DownloadAppsPageVM item in DownloadApps)
            {
                if (item.isAppDownloading)
                {
                    if (item.AppProgressBarValue < 100)
                    {
                        item.AppDescription = "Installing...";
                        item.AppProgressBarValue++;
                    }
                    else
                    {
                        item.AppDescription = "Installing...";
                    }
                }

            }
        }
        #endregion

        #region 获取下载应用列表
        public async void GetDownloadApps()
        {
            foreach (UserAppDataModel item in AppListPageVM.Instance.AppData)
            {
                bool IsExistApp = false;
                foreach (DownloadAppsPageVM item2 in DownloadApps)
                {
                    if (item2.appName == item.AppView.ApplicationName && await AppDetailPageVM.Instance.GetAppLocalStatus(item) == AppLocalStatus.Processing)
                    {
                        IsExistApp = true;
                        break;
                    }
                }
                if (!IsExistApp)
                {
                    if (await AppDetailPageVM.Instance.GetAppLocalStatus(item) == AppLocalStatus.Processing && item.OptType != AppOperationType.Uninstall)
                    {
                        AppLocalStatus status = await AppDetailPageVM.Instance.GetAppLocalStatus(item);
                        DownloadAppsPageVM downloadAppsPageVM = new DownloadAppsPageVM();
                        downloadAppsPageVM.AppName = item.AppView.ApplicationName;
                        downloadAppsPageVM.AppProgressBarValue = 0;
                        downloadAppsPageVM.AppDescription = status.ToString();
                        m_DownloadApps.Add(downloadAppsPageVM);
                    }
                }
            }
        }
        #endregion

        #region 添加应用到下载列表
        public void AddDownloadApps(AppDetailPageVM appDetailPageVM)
        {
            bool IsExistApp = false;
            foreach (DownloadAppsPageVM item in DownloadApps)
            {
                if (item.appName == appDetailPageVM.AppModel.AppView.ApplicationName)
                {
                    IsExistApp = true;
                    break;
                }
            }
            if (!IsExistApp)
            {
                DownloadAppsPageVM downloadAppsPageVM = new DownloadAppsPageVM();
                downloadAppsPageVM.Id = appDetailPageVM.AppModel.AppView.Id;
                downloadAppsPageVM.LogoUrl_Store = appDetailPageVM.AppModel.AppView.LogoUrl_Store;
                downloadAppsPageVM.AppName = appDetailPageVM.AppModel.AppView.ApplicationName;
                downloadAppsPageVM.AppProgressBarValue = 0;
                downloadAppsPageVM.AppDescription = appDetailPageVM.AppModel.LocalStatus.ToString();
                DownloadApps.Add(downloadAppsPageVM);
            }
        }
        #endregion

        #region 移除下载列表中安装完成的应用
        /// <summary>
        /// 移除安装完成的应用
        /// </summary>
        public async void RefreshDownloadApps()
        {
            try
            {
                foreach (UserAppDataModel item in AppListPageVM.Instance.AppData)
                {
                    foreach (DownloadAppsPageVM item2 in DownloadApps)
                    {
                        if ((item2.appName == item.AppView.ApplicationName && await AppDetailPageVM.Instance.GetAppLocalStatus(item) == AppLocalStatus.Installed) || (item2.appName == item.AppView.ApplicationName && AppDetailPageVM.Instance.AppModel.OptStatus == AppOperationStatus.Failed))
                        {
                            DownloadApps.Remove(item2);
                            break;
                        }
                    }
                }
            }
            catch (System.InvalidOperationException)
            {
            }
        }
        #endregion

        #region 暂停/继续下载应用
        public void PauseDownloadApps(string appName, bool isDownload)
        {
            foreach (DownloadAppsPageVM item in DownloadApps)
            {
                if (item.AppName == appName)
                {
                    item.isAppDownloading = isDownload;
                    break;
                }
            }
        }
        #endregion

    }
}
